package com.jiangxjsy.crm.service.impl;

import cn.hutool.core.util.StrUtil;
import com.jiangxjsy.core.common.CrmModule;
import com.jiangxjsy.core.enums.FieldEnum;
import com.jiangxjsy.core.redis.Redis;
import com.jiangxjsy.crm.client.AdminClient;
import com.jiangxjsy.crm.mapper.CrmRoleFieldMapper;
import com.jiangxjsy.crm.service.CrmFieldService;
import com.jiangxjsy.crm.service.CrmRoleFieldService;
import com.jiangxjsy.model.core.entity.UserInfo;
import com.jiangxjsy.model.crm.bo.CrmRoleFieldBO;
import com.jiangxjsy.model.crm.entity.CrmField;
import com.jiangxjsy.model.crm.entity.CrmRoleField;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * wukong-crm-master
 * 蒋胜宇
 * 2025/6/19 15:32
 */

@Service
public class CrmRoleFieldServiceImpl implements CrmRoleFieldService {
    @Resource
    private CrmRoleFieldMapper crmRoleFieldMapper;

    @Resource
    private CrmFieldService crmFieldService;

    @Resource
    private AdminClient adminClient;

    @Resource
    private Redis redis;

    /**
     * 查询未授权字段
     *
     * @param label 标签
     * @param token 用户 token
     * @return 字段列表
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<String> queryNoAuthField(Integer label, String token) {
        List<CrmRoleField> list = queryUserRoleField(label, token);
        list.removeIf(crmRoleField -> crmRoleField.getAuthLevel() > 1);
        List<CrmField> crmFields = crmFieldService.queryHiddenFieldNamesByLabel(label);
        List<String> collect = crmFields.stream().map(field ->
                StrUtil.toCamelCase(field.getFieldName())).collect(Collectors.toList()
        );
        collect.addAll(list.stream().map(field ->
                StrUtil.toCamelCase(field.getFieldName())).collect(Collectors.toList())
        );
        return collect;
    }

    /**
     * 查询用户角色字段
     *
     * @param label 标签
     * @param token 用户 token
     * @return 字段列表
     */
    @Override
    public List<CrmRoleField> queryUserRoleField(Integer label, String token) {
        UserInfo userInfo = redis.get(UserInfo.class, token);
        List<Integer> roleIds = userInfo.getRoles();
        if(roleIds.isEmpty()){
            return Collections.emptyList();
        }

        List<CrmRoleField> list = crmRoleFieldMapper.selectByRoleIdsAndLabel(roleIds, label);
        if (list.isEmpty()) {
            List<Long> roleIdList = adminClient.queryRoleByRoleType(2).getData();
            List<Integer> data = new ArrayList<>();
            for (Long roleId : roleIdList) {
                data.add(Math.toIntExact(roleId));
            }
            data.retainAll(roleIds);
            data.forEach(roleId -> {
                List<CrmRoleFieldBO> ignore = queryRoleField(roleId, label);
            });
            list = crmRoleFieldMapper.selectByRoleIdsAndLabel(roleIds, label);
        }

        return list;
    }

    /**
     * 查询角色字段
     *
     * @param roleId 角色id
     * @param label 标签
     * @return 字段列表
     */
    @Override
    public List<CrmRoleFieldBO> queryRoleField(Integer roleId, Integer label) {
        Integer num = crmRoleFieldMapper.countByRoleIdAndLabel(roleId, label);
        if (num == 0) {
            List<CrmRoleFieldBO> fields = new ArrayList<>();
            List<CrmField> list = crmFieldService.queryCrmFieldsByLabelAndType(label, FieldEnum.DESC_TEXT.getType());
            list.forEach(crmField -> {
                CrmRoleFieldBO roleField = new CrmRoleFieldBO();
                roleField.setRoleId(Long.valueOf(roleId));
                roleField.setLabel(Long.valueOf(label));
                roleField.setFieldId(crmField.getFieldId());
                roleField.setFieldName(crmField.getFieldName());
                roleField.setName(crmField.getName());
                roleField.setAuthLevel(3L);
                roleField.setMaskType(0L);

                switch (label) {
                    case 1: {
                        if ("leads_name".equals(crmField.getFieldName())) {
                            roleField.setOperateType(3L);
                        } else if ("next_time".equals(crmField.getFieldName())) {
                            roleField.setOperateType(4L);
                        } else {
                            roleField.setOperateType(1L);
                        }
                        break;
                    }
                    case 2: {
                        if ("customer_name".equals(crmField.getFieldName())) {
                            roleField.setOperateType(3L);
                        } else if ("next_time".equals(crmField.getFieldName())) {
                            roleField.setOperateType(4L);
                        } else {
                            roleField.setOperateType(1L);
                        }
                        break;
                    }
                    case 3: {
                        if ("customer_id".equals(crmField.getFieldName())) {
                            roleField.setOperateType(4L);
                        } else if ("next_time".equals(crmField.getFieldName())) {
                            roleField.setOperateType(4L);
                        } else {
                            roleField.setOperateType(1L);
                        }
                        break;
                    }
                    case 4: {
                        if (Arrays.asList("name", "unit", "price", "category_id").contains(crmField.getFieldName())) {
                            roleField.setOperateType(3L);
                        } else {
                            roleField.setOperateType(1L);
                        }
                        break;
                    }
                    case 5: {
                        if ("customer_id".equals(crmField.getFieldName())) {
                            roleField.setOperateType(4L);
                        } else {
                            roleField.setOperateType(1L);
                        }
                        break;
                    }
                    case 6: {
                        if ("num".equals(crmField.getFieldName())) {
                            roleField.setOperateType(3L);
                        } else {
                            roleField.setOperateType(1L);
                        }
                        break;
                    }
                    case 7:
                    case 8: {
                        roleField.setOperateType(1L);
                        break;
                    }
                    case 17: {
                        if (Arrays.asList("owner_user_id", "customer_id", "contract_id").contains(crmField.getFieldName())) {
                            roleField.setOperateType(4L);
                        } else {
                            roleField.setOperateType(1L);
                        }
                        break;
                    }
                    case 18: {
                        if (Arrays.asList("contract_money", "contract_id", "customer_id").contains(crmField.getFieldName())) {
                            roleField.setOperateType(4L);
                        } else {
                            roleField.setOperateType(1L);
                        }
                        break;
                    }
                }

                roleField.setFieldType(crmField.getFieldType());
                fields.add(roleField);
            });

            fields.add(new CrmRoleFieldBO(label, roleId, "create_user_name", "创建人", 2, 2, 1));
            fields.add(new CrmRoleFieldBO(label, roleId, "create_time", "创建时间", 2, 2, 1));
            fields.add(new CrmRoleFieldBO(label, roleId, "update_time", "更新时间", 2, 2, 1));

            if (!label.equals(CrmModule.PRODUCT.getType())) {
                fields.add(new CrmRoleFieldBO(label, roleId, "owner_user_name", "负责人", 2, 4, 1));
                fields.add(new CrmRoleFieldBO(label, roleId, "owner_dept_name", "所属部门", 2, 4, 1));
            }

            switch (label) {
                case 1: {
                    fields.add(new CrmRoleFieldBO(label, roleId, "last_content", "最后跟进记录", 2, 2, 1));
                    fields.add(new CrmRoleFieldBO(label, roleId, "last_time", "最后跟进时间", 2, 2, 1));
                    break;
                }
                case 2: {
                    fields.add(new CrmRoleFieldBO(label, roleId, "last_content", "最后跟进记录", 2, 2, 1));
                    fields.add(new CrmRoleFieldBO(label, roleId, "last_time", "最后跟进时间", 2, 2, 1));
                    fields.add(new CrmRoleFieldBO(label, roleId, "receive_time", "负责人获取客户时间", 2, 2, 1));
                    fields.add(new CrmRoleFieldBO(label, roleId, "deal_status", "成交状态", 2, 4, 1));
                    fields.add(new CrmRoleFieldBO(label, roleId, "status", "锁定状态", 2, 2, 1));
                    fields.add(new CrmRoleFieldBO(label, roleId, "pool_day", "距进入公海天数", 2, 2, 1));
                    break;
                }
                case 3: {
                    fields.add(new CrmRoleFieldBO(label, roleId, "last_time", "最后跟进时间", 2, 2, 1));
                    break;
                }
                case 4: {
                    fields.add(new CrmRoleFieldBO(label, roleId, "status", "是否上下架", 3, 4, 1));
                    break;
                }
                case 5: {
                    fields.add(new CrmRoleFieldBO(label, roleId, "type_name", "商机阶段", 2, 2, 1));
                    fields.add(new CrmRoleFieldBO(label, roleId, "status_name", "商机状态组", 2, 2, 1));
                    fields.add(new CrmRoleFieldBO(label, roleId, "last_time", "最后跟进时间", 2, 2, 1));
                    break;
                }
                case 6: {
                    fields.add(new CrmRoleFieldBO(label, roleId, "last_time", "最后跟进时间", 2, 2, 1));
                    fields.add(new CrmRoleFieldBO(label, roleId, "last_content", "最后跟进记录", 2, 2, 1));
                    fields.add(new CrmRoleFieldBO(label, roleId, "received_money", "已收款金额", 2, 2, 1));
                    fields.add(new CrmRoleFieldBO(label, roleId, "unreceived_money", "未收款金额", 2, 2, 1));
                    fields.add(new CrmRoleFieldBO(label, roleId, "check_status", "审核状态", 2, 4, 1));
                    break;
                }
                case 7: {
                    fields.add(new CrmRoleFieldBO(label, roleId, "contractMoney", "合同金额", 2, 2, 1));
                    fields.add(new CrmRoleFieldBO(label, roleId, "check_status", "审核状态", 2, 4, 1));
                    break;
                }
                case 8: {
                    fields.add(new CrmRoleFieldBO(label, roleId, "num", "期数", 2, 2, 1));
                    fields.add(new CrmRoleFieldBO(label, roleId, "real_return_date", "实际回款时间", 2, 2, 1));
                    fields.add(new CrmRoleFieldBO(label, roleId, "real_received_money", "实际回款金额", 2, 2, 1,6));
                    fields.add(new CrmRoleFieldBO(label, roleId, "unreceived_money", "未收款金额", 2, 2, 1,6));
                    fields.add(new CrmRoleFieldBO(label, roleId, "received_status", "回款状态", 2, 2, 1));
                    break;
                }
                default:
                    break;
            }
            Integer ignore = crmRoleFieldMapper.insertBatch(fields);
        }

        return crmRoleFieldMapper.selectRoleFieldList(roleId, label);
    }
}
